package com.example.spider;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

public class postDataDemo {
    public static void main(String[] args) throws Exception {
        //模拟浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //构建带参数的post请求
        //封装数据
        ArrayList<NameValuePair> data = new ArrayList<>();
        data.add(new BasicNameValuePair("q","面"));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(data, StandardCharsets.UTF_8);
        //构建无参请求
        HttpPost httpPost = new HttpPost("https://soso.nipic.com/");
        //设置数据，构建带参数请求
        httpPost.setEntity(formEntity);
        System.err.println(httpPost);
        //发送请求，获得结果
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //解析数据
        if (response.getCode() == 200){
            HttpEntity httpEntity = response.getEntity();
            String res = EntityUtils.toString(httpEntity, "utf8");
            System.out.println(res);
        }else {
            System.err.println("解析失败！");
        }
    }
}
